package com.chianghao.nio.core;

import com.chianghao.nio.core.handle.http.HttpMethod;
import com.chianghao.nio.core.handle.http.HttpRequest;
import com.chianghao.nio.core.handle.http.HttpRequestKey;
import com.chianghao.nio.core.handle.http.HttpRoute;

import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author ChiangHao
 * @date 2022/10/2 11:06
 * @Description:
 */
public class NioService {


    private static List<NioSubReactor> subReactors;
    private static NioReactor reactor;

    private Map<HttpRequestKey,HttpRoute> routeMap = new HashMap<HttpRequestKey,HttpRoute>(10);

    static List<NioSubReactor> getSubReactors(){
        return subReactors;
    }

    public NioService() throws IOException {
        this(null,80, null);
    }


    private NioService addRoute(HttpRoute httpRoute) {
        HttpRequestKey key = new HttpRequestKey(httpRoute.getMethod(),httpRoute.getUrl());
        routeMap.put(key,httpRoute);
        return this;
    }

    public NioService(int port) throws IOException {
        this(null,port, null);
    }


    public NioService(String host,int port, Integer subReactorNum) throws IOException {
        if (subReactorNum == null) {
            subReactorNum = Runtime.getRuntime().availableProcessors();
        }
        reactor = new NioReactor(host,port);

        subReactors = new ArrayList<NioSubReactor>();
        for (int i = 0; i < subReactorNum; i++) {
            subReactors.add(new NioSubReactor(routeMap));
        }
    }


    public void start() {
        System.out.println("启动子reactor");
        subReactors.forEach(sub -> {
            new Thread(sub,"子选择器").start();
        });
        System.out.println("启动主reactor");
        new Thread(reactor,"主选择器").start();

        System.out.println("启动成功");
    }

    public static void main(String[] args) throws IOException {
        new NioService(8090).addRoute(new HttpRoute(HttpMethod.GET,"/asdfad",(req,resp)->{
            try {
                resp.getOutput().write("{\"code\":1}".getBytes(Charset.forName("UTF-8")));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        })).start();
    }


}


